<script setup>
import webConfig from '@/GlobalParas';
import axios from 'axios';
import { computed, ref, watch } from 'vue';
const treeData=ref([]);
const buildTree = (data, parentId = null) => {
    return data
        .filter(item => item.parentFunctionId === parentId)
        .map(item => ({
            title: item.functionName,
            key: item.tableKey,
            children: buildTree(data, item.tableKey)
        }));
}
// 定义childArr存放所有子节点
const childArr = ref([])
// 遍历获取所有子节点
const getChildArr = (data) =>{
  data.forEach((res) => {
    if (res.children && res.children.length > 0) {
      getChildArr(res.children)
    } else {
      childArr.value.push(res.key)
    }
  })
  return childArr.value
}
let props = defineProps({
  roleObj_props:{
    type: Object,
    default: {}
  },
  modelValue: {
    type: Number,
    default: 0
  }
})
// console.log(props.roleObj_props)

const checkedKeysback = ref([]);
const onCheck = (checkedKeys, { halfCheckedKeys }) => {
    const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys];
    checkedKeysback.value = allCheckedKeys;
    // console.log(checkedKeysback.value);
    emit('update:modelValue', 1); //判断为修改过权限树
}; //每次点击将不全选子节点的父节点传入 (若用户未进行任何点击则该数组为空,防止权限丢失使用flag全局判断是否修改过权限树)

const setCheckedKeys = ()=>{ //去除不完全选中的父节点反写进树中
 checkedKeys.value = props.roleObj_props.roleFunctions
        .map(fun => fun.function_id)
        .filter(key => childArr.value.includes(key));
}

const getAllRoleFunction = ()=>{ //获取所有功能并构建树
let url = webConfig.postUrl + '/systemFunction/getAllFunctions'
return axios.post(url).then(res => {
    treeData.value = buildTree(res.data)
    // console.log(treeData)
    getChildArr(treeData.value)
    // console.log(childArr)
})
}

getAllRoleFunction().then(()=>{setCheckedKeys();});

const emit=defineEmits(["editInfo",'update:modelValue']);
const onFinish = values => {
    // console.log('Success:', values);
   let role = {
    tableKey: props.roleObj_props.TableKey,
    deptId:props.roleObj_props.dept_id,
    roleName: props.roleObj_props.role_name,
    sort: '',
    flagDel: 0
}
  emit("editInfo", role, checkedKeysback.value)
  // checkedKeysback.value=[];
};
const onFinishFailed = errorInfo => {
  console.log('Failed:', errorInfo);
};

const expandedKeys = ref(['001','002','003']);
const selectedKeys = ref([]);
let checkedKeys = ref([]);
watch(
  () => props.roleObj_props.TableKey,
  (newVal, oldVal) => {
    // console.log('role_name changed:', newVal);
    setCheckedKeys()
    emit('update:modelValue', 0);
  }
);

</script>

<template>
    <a-form :model="props.roleObj_props" :label-col="{ span: 4 }" @finish="onFinish" @finishFailed="onFinishFailed">
        <a-form-item :wrapper-col="{ span: 14 }" label="角色名" name="role_name"
            :rules="[{ required: true, message: '请输入角色名' },{ min: 0, max: 50,message: '字数不得超过50'}]">
            <a-input v-model:value="props.roleObj_props.role_name" />
        </a-form-item>
        <a-form-item label="权限分配" style="margin-left: 10px;">
            <div style="display: flex; justify-content: space-between;">
                <div>
                    <a-tree @check="onCheck" v-model:expandedKeys="expandedKeys" 
                        v-model:checkedKeys="checkedKeys" checkable :tree-data="treeData">
                        <template #title="{ title }">
                            {{ title }}
                        </template>
                    </a-tree>
                </div>
                <a-button type="primary" html-type="submit" style="margin-right: 60px; align-self:flex-end;" >确认</a-button>
            </div>
        </a-form-item>
    </a-form>
</template>

<style scoped>

</style>